package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.common.ThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 素材上传
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //1. 参数合法性校验
        if (multipartFile.isEmpty() || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // TODO 校验文件是否是图片类型

        String contentType = multipartFile.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "上传的文件不是图片类型");
        }

        // 可以进一步检查文件扩展名是否为常见的图片格式
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename == null || !originalFilename.matches(".*\\.(jpg|jpeg|png|gif|bmp|tiff)$")) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "上传的文件不是支持的图片格式");
        }


        //2. 生成文件的唯一名称
        String fileNamePrefix = UUID.randomUUID().toString().replace("-", "");
        // 获取原始文件名称
        //String originalFilename = multipartFile.getOriginalFilename();
        // 获取文件后缀
        int index = originalFilename.lastIndexOf(".");
        String fileNamePostfix = originalFilename.substring(index);
        String fileName = fileNamePrefix + fileNamePostfix;


        //3. 将上传文件到minio 得到url
        try {
            String url = fileStorageService.uploadImgFile("", fileName, multipartFile.getInputStream());

            //4. 构建素材数据   （思考：怎么获取到当前用户的userId? 先在微服务中 写获取userId的方案）
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(url);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType(0); // 0 图片 1视频
            wmMaterial.setIsCollection(0); // 0 未收藏 1 收藏
            wmMaterial.setUserId(ThreadLocalUtil.getUserId());
            this.save(wmMaterial);

            //5. 响应素材数据（目的是为了回显）
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传素材失败！！！");

        }
    }

    /**
     * 素材列表查询
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        log.info("素材列表查询开始  dto ====>>>{}",dto);
        //1. 参数校验 设置分页参数默认值
        dto.checkParam();

        //2. 拼接查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, ThreadLocalUtil.getUserId());
        if (dto.getIsCollection() > 0) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //3. 分页查询
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        this.page(page, queryWrapper);

        //4. 构建返回结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }


    /**
     * 素材取消收藏
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        log.info("素材取消收藏开始  id ====>>>{}",id);
        // 健壮性判断
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 修改收藏状态
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(0);  // 0 未收藏 1 收藏
        boolean b = this.updateById(wmMaterial);
        return b ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 素材收藏
     */
    @Override
    public ResponseResult collect(Integer id) {
        log.info("素材收藏开始  id ====>>>{}",id);
        // 健壮性判断
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 修改收藏状态
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection(1);  // 0 未收藏 1 收藏
        boolean b = this.updateById(wmMaterial);
        return b ? ResponseResult.okResult(AppHttpCodeEnum.SUCCESS) : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }


    /**
     * 删除素材
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        log.info("删除素材开始  id ====>>>{}",id);
        // 健壮性判断
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 删除 数据库 素材
        WmMaterial one = this.getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getId, id));
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        String url = one.getUrl();
        this.removeById(id);

        // 删除 minIO素材

        try {
            fileStorageService.delete(url);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"删除素材失败！！！");
        }
    }
}
